//
//  CollectionViewController.m
//  Linkage
//
//  Created by LeeJay on 16/8/22.
//  Copyright © 2016年 LeeJay. All rights reserved.
#import "CollectionCategoryModel.h"
#import "CollectionViewCell.h"
#import "CollectionViewController.h"
#import "CollectionViewHeaderView.h"
#import "LJCollectionViewFlowLayout.h"
#import "LeftTableViewCell.h"
#import "Header.h"
#import "Global1.h"
#import "LampController.h"
#import "AirconditionController.h"
#import "NewTVController.h"
#import "DVDController.h"
#import "CurtainsController.h"
#import "MusicController.h"
#import "AirconditionController.h"
#import "eventAction.h"
#import "AppDelegate.h"
#import "GKBEquipmentsManager.h"

@interface CollectionViewController () <UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegateFlowLayout,
UICollectionViewDataSource,MyCellDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSMutableArray *collectionDatas;
@property (nonatomic, strong) LJCollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) UIView *lineV;
@property (nonatomic, strong) AppDelegate *appDelegate;


@property(nonatomic,strong)NSMutableArray *tableViewArr;

@property(nonatomic,strong)NSMutableArray *collectionArr;

@property(nonatomic,strong)NewEquipment *equipment;

@end

@implementation CollectionViewController
{
    NSInteger _selectIndex;
    BOOL _isScrollDown;
}
- (void)viewDidLoad
{
    [super viewDidLoad];

    self.roomNames = [NSMutableArray array];
    self.rooms = [NSMutableDictionary dictionary];
    self.roomNamess = [NSMutableArray array];
    self.roomss = [NSMutableDictionary dictionary];
    self.sceneArray = [NSMutableArray array];
    self.areaEquipments = [NSMutableArray array];
    self.equipments = [NSMutableArray array];
    self.protectArray = [NSMutableArray array];
    
    self.tableViewArr =[NSMutableArray array];
    
    self.collectionArr =[NSMutableArray array];
    
     _houseArray = [[NSMutableArray alloc]init];
//    [self setNavigationTitleView:@"Smart Home"];
    // 设置全局UINavigationBar背景色
    _selectIndex = 0;
    _isScrollDown = YES;
    _appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;


//    self.edgesForExtendedLayout = UIRectEdgeNone;
//    self.extendedLayoutIncludesOpaqueBars = NO;
//    self.automaticallyAdjustsScrollViewInsets = NO;

    
    UIImage *image = [UIImage imageNamed:@"mainbg"];
    self.view.layer.contents = (id) image.CGImage;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH/3, SCREEN_HEIGHT)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [UIView new];
    _tableView.rowHeight = (SCREEN_HEIGHT-64-80)/4;
    _tableView.backgroundColor =[UIColor clearColor];
    _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorColor = [UIColor clearColor];
    [_tableView registerClass:[LeftTableViewCell class] forCellReuseIdentifier:kCellIdentifier_Left];
    
    [self.view addSubview:self.tableView];
    
    _lineV = [[UIView alloc]initWithFrame:(CGRect){SCREEN_WIDTH/3+1,64,.3,screenHeight}];
    _lineV.backgroundColor = [UIColor colorWithRGBColorByString:@"#445ba0"];
    [self.view addSubview:_lineV];
    
    [self.view addSubview:self.collectionView];

    //左边数据
//    [self equipmentState:^{
//        [self loadList];
//    }];
}

//- (void)equipmentState:(void(^)(void))endresult
//{
//    NSString *refresh = @"2";
//    
//    NSString *sessionId = [LoginController1 sessionID];
//    NSString *fomat = @"[{\"sessionId\":\"%@\",\"refresh\":\"%@\"}]";
//    NSString *body = [NSString stringWithFormat:fomat, sessionId, refresh];
//    [WebServices requestSynStartOrder:@"getEquipmentState" body:body result:^(NSDictionary *dic) {
//        NSNumber *result = [dic objectForKey:@"result"];
//        NSArray *states = [dic objectForKey:@"states"];
//        if (result.integerValue == 0) {
//            [self.allStatesM removeAllObjects];
//            [self.allStatesM addObjectsFromArray:states];
//        }
//        if(endresult)
//        {
//            endresult();
//        }
//    }];
//    
//}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (_appDelegate.curRooms && _appDelegate.curRooms.count) {
        [self.rooms removeAllObjects];
        [self.roomNames removeAllObjects];
        [self.rooms setDictionary:_appDelegate.curRooms];
        [self.roomNames addObjectsFromArray:self.rooms.allKeys];
    }
    
    if (_appDelegate.leftArray && _appDelegate.leftArray.count) {
        [self.tableViewArr removeAllObjects];
        [self.tableViewArr addObjectsFromArray:_appDelegate.leftArray];
        [self.tableView reloadData];
    }
    
    if (_appDelegate.rightArray && _appDelegate.rightArray.count) {
        [self.collectionArr removeAllObjects];
        [self.collectionArr addObjectsFromArray:_appDelegate.rightArray];
        [self.collectionView reloadData];
    }
    
}

- (void)loadList
{
    [self areaEquipmentList];
    [self equipmentList];
    
}

#pragma mark - 区域数据
- (void)areaEquipmentList
{
    
    NSString *sessionId = [LoginController1 sessionID];
    
    NSString *fomat = @"[{\"sessionId\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, sessionId];
    NSString *errorType = [OperationTip errorType:ErrorTypeNetworkFail];
    
    [WebServices requestStartOrder:@"getRelevanceHosts" body:body target:self action:@selector(areaEquipmentListEnd:) errorTip:errorType];
}

#pragma mark - 电器设备数据
- (void)equipmentList
{
    NSInteger sortType = [SystemSettting sortType];
    NSString *sessionId = [LoginController1 sessionID];
    
    NSString *fomat = @"[{\"sessionId\":\"%@\", \"obway\":\"%d\"}]";
    NSString *body = [NSString stringWithFormat:fomat, sessionId, sortType];
    NSString *errorType = [OperationTip errorType:ErrorTypeNetworkFail];
    
    [WebServices requestStartOrder:@"getEquipmentList" body:body target:self action:@selector(equipmentListEnd:) errorTip:errorType];
}

- (void)equipmentListEnd:(NSDictionary *)dic
{
    NSLog(@"equipmentListEnd：%@", dic);
    // NSString *result = [dic objectForKey:@"result"];
    NSNumber *result = [dic objectForKey:@"result"];
    NSArray *data = [dic objectForKey:@"data"];
    //    self.equipments = data;
    if (self.equipments) {
        [self.equipments removeAllObjects];
    }
    else
    {
        self.equipments = [[NSMutableArray alloc] init];
        
    }
    self.equipments = data;
    if ([data count]>0) {
        NSMutableArray *array = [NSMutableArray array];
        for (NSDictionary *dic in data) {
            NSMutableDictionary *mutDic = [NSMutableDictionary dictionaryWithDictionary:dic];
            [array addObject:mutDic];
        }
        self.equipments = array;
    }
    //    NSLog(@"%@,%@", result, sessionId);
    [self.roomNames removeAllObjects];
    [self.rooms removeAllObjects];
    [self.protectArray removeAllObjects];
    if (result.integerValue == 0)
    {
        NSString *version = [dic objectForKey:@"version"];
        if (version && [version isEqualToString:@"ds"]) {
            //ds:  此主机有定时功能 de:  此主机为默认旧主机，没有定时功能
            // [SettingController setHaveTimeSetting:YES];
        }
        else{
            // [SettingController setHaveTimeSetting:NO];
        }
        NSString *saveEqusFile = [AppFile documentsPath:@"euqs.bat"];
        [dic writeToFile:saveEqusFile atomically:YES];
        for (NSDictionary *equ in data) {
            NSString *name = [equ objectForKey:@"name"];
            NSString *type = [equ objectForKey:@"type"];
            NSString *switchId = [equ objectForKey:@"switchId"];
            NSString *tagName = [equ objectForKey:@"tagName"];
            
            //            NSString *sting = [NSString stringWithCString:tagName.UTF8String encoding:NSUTF8StringEncoding];
            //            NSLog(@"r:%@",sting);
            
            NSString *regulate = [equ objectForKey:@"regulate"];
            NewEquipment *equipment = [[NewEquipment alloc]init];
            [equipment setName:name];
            [equipment setType:type];
            [equipment setSwitchId:switchId];
            [equipment setTagName:tagName];
            [equipment setRegulate:regulate];
            [equipment setState:kStateOFF];
            
            if ([type isEqualToString:@"9"]) {//安防
                [self.protectArray addObject:equipment];
            }
            else
            {
                NSMutableArray *room = [self.rooms objectForKey:tagName];
                if (room) {
                    [room addObject:equipment];
                }
                else
                {
                    [self.roomNames addObject:tagName];
                    NSMutableArray *room = [[NSMutableArray alloc]init];
                    [room addObject:equipment];
                    [self.rooms setObject:room forKey:tagName];
                    [room release];
                }
            }
            [equipment release];
        }

        [self getUserCameraList:^{
            [_houseArray removeAllObjects];
            [self initRoomsMenu];
            [self initDevicesTwo];
            
        }];
    }
    else
    {
        NSString *errorType = [OperationTip errorType:ErrorTypeServerReturnFail];
        [iToast showTip:errorType gravity:iToastGravityBottom];
    }
    
}

- (void)initDevicesTwo
{
    NSInteger pages = [self pageCount];
    
//    [_scrollPages removeAllObjects];
//    
//    for(UIView *view in devicesScrollView.subviews)
//    {
//        [view removeFromSuperview];
//    }
    
    
   // CGFloat contentHeight = houseMenuScrollView.contentSize.height;
    NSInteger startX = 15;
    NSInteger rowMax = kDeviceMenuWidth/kViewWidth;//每页横排可容纳个数
    
    for (int page = 0; page<pages; page++) {
        UIScrollView *pageView = [[UIScrollView alloc]initWithFrame:CGRectMake(page * kDeviceMenuWidth, 0, kDeviceMenuWidth, kMainFrameHeight)];
        for (int room = 0; room <[_houseArray count]; room++) {// room 是y轴
            HouseButton *house = [_houseArray objectAtIndex:room];
            NSInteger count = [house.devices count];
            int deveceIndex = page*rowMax;//当前页起始电器
            int capacityMax = deveceIndex+rowMax;//当前面可放置的最后一个电器
            int maxDevces = capacityMax<count?(capacityMax):count;//当前页可容纳电器总数VS当电器总数
            
            if (deveceIndex>0 && deveceIndex < count) {//当大于一页，有向左的箭头
                UIImageView *toLeft = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"toLeft.png"]];
                [toLeft setFrame:CGRectMake(0, 0, 8, 16)];
                [toLeft setCenter:CGPointMake(startX/2, room*kViewHeight + kIconHeight/2)];
                [pageView addSubview:toLeft];
                [toLeft release];
            }
            //还有多余电器，提示向右箭头
            if (capacityMax < count) {//还有多余电器，放在下一页
                UIImageView *toRight = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"toRight.png"]];
                [toRight setFrame:CGRectMake(0, 0, 8, 16)];
                [toRight setCenter:CGPointMake(kDeviceMenuWidth - 15, room*kViewHeight + kIconHeight/2)];
                [pageView addSubview:toRight];
                [toRight release];
            }
            
            for (; deveceIndex<maxDevces; deveceIndex++) {//device是x轴
                // NSArray *array = house.devices;
                
                // NSLog(@"%d, %@", count, array);
                if (deveceIndex<[house.devices count]) {
                    CGRect rect = CGRectMake(startX + (deveceIndex%rowMax)*kViewWidth, room*kViewHeight, kViewWidth, kViewHeight);
                    NewEquipment *equipment = [house.devices objectAtIndex:deveceIndex];
                    DeviceView *deviceView = [[DeviceView alloc]initWithFrame:rect withEqu:equipment];
                    BOOL open = NO;
                    if ([equipment.state isEqualToString:@"1"]) {
                        open = YES;
                    }
                    if ([equipment.state isEqualToString:@"2"]) {
                        open = NO;
                    }
                    [deviceView setDeviceOn:open];
                    [pageView addSubview:deviceView];
                    [deviceView release];
                }
                
            }
            
        }
    }
    
   
}

- (NSInteger)pageCount
{
    NSInteger maxCount = 0;
    for (HouseButton *house in _houseArray) {
        NSInteger count = [house.devices count];
        if (maxCount < count) {
            maxCount = count;
        }
    }
    NSInteger page = (maxCount - 1)/5 + 1;
    return page;
}
#pragma mark - 摄像头数据

- (void)getUserCameraList:(void(^)(void))endresult
{
    NSString *sessionId = [LoginController1 sessionID];
    NSString *fomat = @"[{\"sessionId\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, sessionId];
    // [WebServices setShowConnectting:NO];//关闭提示
    
    [WebServices requestSynStartOrder:@"getUserCameraList" body:body result:^(NSDictionary *dic) {
        [WebServices setShowConnectting:NO];
        NSNumber *result = [dic objectForKey:@"result"];
        if (result.integerValue == 0) {
            NSArray *data = [dic objectForKey:@"cameraGroup"];
            if (data) {
                self.cameraGroup = [NSMutableArray arrayWithArray:data];
            }
        }
        if (endresult) {
            endresult();
        }
    }];
}

- (void)initRoomsMenu
{
    //    CGRect rect = CGRectMake(2, 10, 56, 56);
        int i = 0;
    for (NSString *key in self.roomNames)
    {
        NSLog(@"%@---", key);
        
        [self.tableViewArr addObject:key];
        NSArray *arr = [self.rooms objectForKey:key];
        [self addHouseMenu:i++ title:key image:nil selected:nil devices:arr];
    }
    
    [self setNavigationTitleView:self.roomNames[0]];
    
    [self.tableView reloadData];
    id c =   [self.rooms valueForKey:self.roomNames[0]];
    self.collectionArr = c;
    [self.collectionView reloadData];
    
}

- (void)addHouseMenu:(NSInteger)index title:(NSString *)title image:(NSString *)img selected:(NSString *)selectedImg devices:(NSArray*)array
{
    HouseButton *but = [[HouseButton alloc]init];//[HouseButton buttonWithType:UIButtonTypeRoundedRect];
    CGRect rect = CGRectMake(10, (kHouseMenuHeight)*index, kHouseButtonWidth, kHouseButtonHeight);
    [but setFrame:rect];
    [but setTag:index];
    [but setName:title];
    [but setImgStr:img];
    [but setSelectedImg:selectedImg];
    //NSArray *deArray = [array copy];
    [but setDevices:array];
    //[deArray release];
    if ([title isEqualToString:@"区域"]) {
        [but.titleLabel setFont:[UIFont boldSystemFontOfSize:22.0]];
    }else{
        [but.titleLabel setFont:[UIFont boldSystemFontOfSize:22.0]];
    }
    [but.titleLabel setAdjustsFontSizeToFitWidth:YES];
    if ([title length]>=3) {
        
        [but.titleLabel setFont:[UIFont boldSystemFontOfSize:15.0]];
        [but.titleLabel setNumberOfLines:2];
        NSLog(@"title = %@",title);
    }

    [but setTitle:title forState:UIControlStateNormal];
    [but setBackgroundImage:[UIImage imageNamed:img] forState:UIControlStateNormal];
    [but setBackgroundImage:[UIImage imageNamed:selectedImg] forState:UIControlStateHighlighted];
    [but setState:buttonStateNormal];
    [but addTarget:self action:@selector(houseAction:) forControlEvents:UIControlEventTouchUpInside];
    //    [but addTarget:self action:@selector(houseOutsize:) forControlEvents:UIControlEventTouchDragOutside];
    [_houseArray addObject:but];
    //[houseMenuScrollView addSubview:but];
    [but release];
}


-(void)getInfoDataForKey:(NSMutableDictionary *)dic
{
    NSDictionary *myDataDic = dic;
}

- (void)areaEquipmentListEnd:(NSDictionary *)dic
{
    
    NSLog(@"equipmentListEnd：%@", dic);
    NSArray *data = [dic objectForKey:@"relevanceHosts"];
    //    NSLog(@"data主机名称＝＝＝＝%@",data);
    if (self.areaEquipments) {
        [self.areaEquipments removeAllObjects];
    }
    else
    {
        self.areaEquipments = [[NSMutableArray alloc] init];
    }
    for (NSDictionary *equ in data) {
        NSString *displayName = [equ objectForKey:@"displayName"];
        NSString *orderId = [equ objectForKey:@"orderId"];
        NSString *relevanceUserName = [equ objectForKey:@"relevanceUserName"];
        NSString *relevanceUserPass = [equ objectForKey:@"relevanceUserPass"];
        NSString *hostnum = [equ objectForKey:@"relevanceHostnum"];
        //        NSLog(@"主机名称＝＝＝＝%@",relevanceUserName);
        //        NSString *regulate = [equ objectForKey:@"regulate"];
        NewEquipment *equipment = [[NewEquipment alloc]init];
        [equipment setName:displayName];
        [equipment setOrderId:orderId];
        [equipment setRelevanceUserName:relevanceUserName];
        [equipment setRelevanceUserPass:relevanceUserPass];
        [equipment setType:@"14"];
        //        [equipment setRegulate:regulate];
        [equipment setState:kStateOFF];
        [equipment setSwitchId:hostnum];
        equipment.target = self;
        //        equipment.selector = @selector(openAreaInfo:);
        if ([hostnum isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"hostnum"]]) {
            [self.areaEquipments insertObject:equipment atIndex:0];
        }else{
            [self.areaEquipments addObject:equipment];
        }
        [equipment release];
    }
}


/**
 *  @brief  根据颜色生成纯色图片
 *
 *  @param color 颜色
 *
 *  @return 纯色图片
 */
-(UIImage *)Color1:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}


- (void)setNav
{
    UINavigationBar *bar = [UINavigationBar appearance];
    //设置显示的颜色
    bar.barTintColor = [UIColor colorWithRGBColorByString:@"#343f8d"];
    //设置字体颜色
    bar.tintColor = [UIColor whiteColor];
    [bar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    //或者用这个都行
    //    [bar setTitleTextAttributes:@{UITextAttributeTextColor : [UIColor whiteColor]}];
    
}

#pragma mark - Getters

- (NSMutableArray *)dataSource
{
    if (!_dataSource)
    {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (NSMutableArray *)collectionDatas
{
    if (!_collectionDatas)
    {
        _collectionDatas = [NSMutableArray array];
    }
    return _collectionDatas;
}

#pragma mark--tableView懒加载数据

- (LJCollectionViewFlowLayout *)flowLayout
{
    if (!_flowLayout)
    {
        _flowLayout = [[LJCollectionViewFlowLayout alloc] init];
        _flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _flowLayout.minimumInteritemSpacing = 0;
        _flowLayout.minimumLineSpacing = 0;
    }
    return _flowLayout;
}

- (UICollectionView *)collectionView
{
    if (!_collectionView)
    {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/3+1, 64,(SCREEN_WIDTH)*2/3, SCREEN_HEIGHT-64-50) collectionViewLayout:self.flowLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView setBackgroundColor:[UIColor clearColor]];
        //注册cell
        [_collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:kCellIdentifier_CollectionView];
        //注册分区头标题
        [_collectionView registerClass:[CollectionViewHeaderView class]
            forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                   withReuseIdentifier:@"CollectionViewHeaderView"];
    }
    return _collectionView;
}

#pragma mark - UITableView DataSource DelegateX
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tableViewArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LeftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_Left forIndexPath:indexPath];
    [cell.typeNameBtn setTitle:[self.tableViewArr objectAtIndex:indexPath.row] forState:UIControlStateNormal];
    [cell.typeNameBtn setBackgroundImage:[self setImageByName:[self.tableViewArr objectAtIndex:indexPath.row]] forState:UIControlStateNormal];
    [cell.typeNameBtn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
//    cell.backgroundColor = [UIColor redColor];
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor =[UIColor clearColor];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _selectIndex = indexPath.row;
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_selectIndex inSection:0]
                          atScrollPosition:UITableViewScrollPositionTop animated:YES];
    
    id c =   [self.rooms valueForKey:self.roomNames[indexPath.row]];
    self.collectionArr = c;
    [self.collectionView reloadData];
}

#pragma mark --设置区域图片
- (UIImage *)setImageByName:(NSString *)areaName{
    if (areaName && !areaName.length)
        return nil;
    
    if([areaName isEqualToString:@"会议室"])
    {
        return [UIImage imageNamed:@"huiyishi_bg"];
    }
    else if([areaName isEqualToString:@"花园"])
    {
        return [UIImage imageNamed:@"huayuan_bg"];
    }
    else if([areaName isEqualToString:@"接待室"])
    {
        return [UIImage imageNamed:@"jiedaishi_bg"];
    }
    else if([areaName isEqualToString:@"前台"])
    {
        return [UIImage imageNamed:@"qiantai_bg"];
    }
    else
    {
        return [UIImage imageNamed:@"jiedaishi_bg"];
    }
    return nil;
}

#pragma mark - 解决点击 TableView 后 CollectionView 的 Header 遮挡问题

- (void)scrollToTopOfSection:(NSInteger)section animated:(BOOL)animated
{
    CGRect headerRect = [self frameForHeaderForSection:section];
    CGPoint topOfHeader = CGPointMake(0, headerRect.origin.y - _collectionView.contentInset.top);
    [self.collectionView setContentOffset:topOfHeader animated:animated];
}

- (CGRect)frameForHeaderForSection:(NSInteger)section
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:section];
    UICollectionViewLayoutAttributes *attributes = [self.collectionView.collectionViewLayout layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader atIndexPath:indexPath];
    return attributes.frame;
}

#pragma mark - UICollectionView DataSource Delegate

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.collectionArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCellIdentifier_CollectionView forIndexPath:indexPath];
    cell.layer.borderColor =[UIColor colorWithRGBColorByString:@"#445ba0"].CGColor;
    cell.layer.borderWidth = 0.5;
    NewEquipment *model = self.collectionArr[indexPath.row];
    cell.model = model;
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat fWidth,fHeight;
    if (IS_IPAD) {
        fWidth = 2*(SCREEN_WIDTH-0.4)/9;
        fHeight = fWidth;
    } else{
        fWidth = (SCREEN_WIDTH-0.2)/3;
        fHeight = 125;
    }
    
    return CGSizeMake(fWidth,fHeight);
}

// CollectionView分区标题即将展示
- (void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath
{
    // 当前CollectionView滚动的方向向上，CollectionView是用户拖拽而产生滚动的（主要是判断CollectionView是用户拖拽而滚动的，还是点击TableView而滚动的）
    if (!_isScrollDown && (collectionView.dragging || collectionView.decelerating))
    {
        [self selectRowAtIndexPath:indexPath.section];
    }
}

//// CollectionView分区标题展示结束
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(nonnull UICollectionReusableView *)view forElementOfKind:(nonnull NSString *)elementKind atIndexPath:(nonnull NSIndexPath *)indexPath
{
    // 当前CollectionView滚动的方向向下，CollectionView是用户拖拽而产生滚动的（主要是判断CollectionView是用户拖拽而滚动的，还是点击TableView而滚动的）
    if (_isScrollDown && (collectionView.dragging || collectionView.decelerating))
    {
        [self selectRowAtIndexPath:indexPath.section + 1];
    }
}

// 当拖动CollectionView的时候，处理TableView
- (void)selectRowAtIndexPath:(NSInteger)index
{
    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
}

#pragma mark - UIScrollView Delegate
// 标记一下CollectionView的滚动方向，是向上还是向下
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    static float lastOffsetY = 0;
    
    if (self.collectionView == scrollView)
    {
        _isScrollDown = lastOffsetY < scrollView.contentOffset.y;
        lastOffsetY = scrollView.contentOffset.y;
    }
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NewEquipment *model = self.collectionArr[indexPath.row];
    self.equipment = model;
    [self getPageByType:model];
}

-(void)getPageByType:(NewEquipment *)model
{
    switch ([model.type intValue]) {
        case 1://灯
            if ([model.regulate integerValue] == 1) {
                [self.navigationController pushViewController:[[LampController alloc] initWithEquipment:self.equipment] animated:YES];
            } else {
                BOOL equipmentState;
                if ([model.state integerValue] == 1) {//on
                    equipmentState = NO;
                } else {
                    equipmentState = YES;
                }
                __weak typeof(self) weakSelf = self;
                [eventAction electricCompantWithOrder:equipmentState swtichId:model.switchId result:^(NSDictionary *dic) {
                    __strong __typeof(&*weakSelf)strongSelf = weakSelf;
                    for(int i=0;i<strongSelf.collectionArr.count;i++)
                    {
                        NewEquipment *equipment = strongSelf.collectionArr[i];
                        NSString *modelSwitchID = model.switchId;
                        NSString *arrSwitchID = equipment.switchId;
                        BOOL isA = [modelSwitchID isEqualToString:arrSwitchID];
                        if(isA)
                        {
                            if ([equipment.state integerValue]== 1) {
                                equipment.state = @"2";
                            } else {
                                equipment.state = @"1";
                            }
                            [strongSelf.collectionArr replaceObjectAtIndex:i withObject:equipment];
                            break;
                        }
                    }
                    [self.collectionView reloadData];
                    AppDelegate *appdelegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
                    appdelegate.rightArray = [self.collectionArr copy];
                    
                    [[GKBEquipmentsManager shareInstance]setEquipmentsArray:[self.collectionArr copy]];
                    
                }];
            }
            break;
       case 5://窗帘
            [self.navigationController pushViewController:[[CurtainsController alloc] initWithEquipment:self.equipment] animated:YES];
            break;
        case 2://空调
            [self.navigationController pushViewController:[[AirconditionController alloc] initWithEquipment:self.equipment] animated:YES];
            break;
       case 3://电视 暂时不调
            [self.navigationController pushViewController:[[NewTVController alloc] initWithEquipment:self.equipment] animated:YES];
            break;
        case 4://音响 不调
            [self.navigationController pushViewController:[[DVDController alloc] initWithEquipment:self.equipment] animated:YES];
            break;
        case 7://花地浇花 不调
            [self.navigationController pushViewController:[[DVDController alloc] initWithEquipment:self.equipment] animated:YES];
            break;
        case 8://其它 要调
            [self.navigationController pushViewController:[[DVDController alloc] initWithEquipment:self.equipment] animated:YES];
            break;
        case 10://背影音乐 要调
            [self.navigationController pushViewController:[[MusicController alloc] initWithEquipment:self.equipment]animated:YES];
            break;

        default:
            break;
    }
}

-(void)click:(UIButton *)sender
{
    UIView *contentView = [sender superview];
    LeftTableViewCell *cell = (LeftTableViewCell *)[contentView superview];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    _selectIndex = indexPath.row;
    
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_selectIndex inSection:0]
                          atScrollPosition:UITableViewScrollPositionTop animated:YES];
    
    // NSLog(@"--index.row--%@",self.roomNames[indexPath.row]);
    
    id c =   [self.rooms valueForKey:self.roomNames[indexPath.row]];
    self.collectionArr = c;
    [self setNavigationTitleView:[self.tableViewArr objectAtIndex:indexPath.row]];
    [self.collectionView reloadData];
    
}
@end
